/**
 * 
 */
package com.hfjyz.exam.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.hfjyz.exam.command.ExamCommand;
import com.hfjyz.exam.service.PaperService;
import com.hfjyz.exam.util.ValidatorUtil;

/**
 *
 */
public class ExamController extends SimpleFormController {
	private PaperService paperService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject
	 * (javax.servlet.http.HttpServletRequest)
	 */
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		HttpSession session = request.getSession();
		Object cmd = session.getAttribute(getFormSessionAttributeName(request));
		if (cmd != null) {
			return cmd;
		}
		return super.formBackingObject(request);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.SimpleFormController#referenceData
	 * (javax.servlet.http.HttpServletRequest, java.lang.Object,
	 * org.springframework.validation.Errors)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		ExamCommand cmd = (ExamCommand) command;
		String pid = request.getParameter("paperId");
		if (!ValidatorUtil.isEmpty(pid)) {
			cmd.setPid(Integer.valueOf(pid));
		}
		return paperService.initExam(request, cmd, errors);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax
	 * .servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
	 * java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		ExamCommand cmd = (ExamCommand) command;
		paperService.exam(request, cmd, errors);
		if (errors.hasErrors()) {
			return new ModelAndView(getFormView(), errors.getModel());
		}

		return new ModelAndView(new RedirectView("examResult.action"),
				errors.getModel());
	}

	/**
	 * @return the paperService
	 */
	public PaperService getPaperService() {
		return paperService;
	}

	/**
	 * @param paperService
	 *            the paperService to set
	 */
	public void setPaperService(PaperService paperService) {
		this.paperService = paperService;
	}
}
